package cn.hackcloud.netty.codec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.ByteBuffer;

import org.msgpack.annotation.Message;

/**
 * java序列化对比
 * 
 * @author Administrator
 *
 */
@Message
public class UserInfo implements Serializable {
	private static final long serialVersionUID = 1L;
	String userName;
	int userId;

	public UserInfo(String userName, int userId) {
		super();
		this.userName = userName;
		this.userId = userId;
	}

	@Override
	public String toString() {
		return "UserInfo [userName=" + userName + ", userId=" + userId + "]";
	}

	public byte[] codec() {
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		byte[] value = this.userName.getBytes();
		buffer.putInt(value.length);
		buffer.put(value);
		buffer.putInt(this.userId);
		buffer.flip();
		value = null;
		byte[] bytes = new byte[buffer.remaining()];
		buffer.get(bytes);
		return bytes;

	}

	public byte[] codec(ByteBuffer buffer) {
		buffer = ByteBuffer.allocate(1024);
		byte[] value = this.userName.getBytes();
		buffer.putInt(value.length);
		buffer.put(value);
		buffer.putInt(this.userId);
		buffer.flip();
		value = null;
		byte[] bytes = new byte[buffer.remaining()];
		buffer.get(bytes);
		return bytes;

	}

	public static void main(String[] args) throws Exception {
		UserInfo user = new UserInfo("赖军", 26);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream os = new ObjectOutputStream(bos);
		os.writeObject(user);
		os.flush();
		os.close();
		byte[] b = bos.toByteArray();
		System.out.println("JDK serializable length:" + b.length);
		System.out.println("byte array serializable length:" + user.codec().length);
		ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(user.codec()));
		UserInfo readObject = (UserInfo) inputStream.readObject();
		System.out.println(readObject);
	}
}
